<template>
  <div class="main">
    <div class="title">
      <a href="/login">登录</a>
      <span>|</span>
      <a class="active" href="/register">注册</a>
    </div>

    <div class="sign-up-container">
      <el-form ref="userForm" :model="params" :rules="rules">

        <el-form-item class="input-prepend restyle" prop="nickname"
        >
          <div>
            <el-input type="text" placeholder="你的昵称" v-model="params.nickname"/>
            <i class="iconfont icon-user"/>
          </div>
        </el-form-item>
        <!-- 手机注册-->
        <el-form-item v-if="isMobile" class="input-prepend restyle no-radius" prop="mobile"
                      :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{validator: checkPhone, trigger: 'blur'}]">
          <div>
            <el-input type="text" placeholder="手机号" v-model="params.mobile"/>
            <i class="iconfont icon-phone"/>
          </div>
        </el-form-item>
        <!--邮箱-->

        <el-form-item v-else class="input-prepend restyle" prop="email" :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]">
          <div>
            <el-autocomplete
              style="width: 300px"
              v-model="params.email"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :trigger-on-focus="false"
              @select="handleSelect"
            >
              <template slot-scope="{ item }">
                <span class="addr">{{ item }}</span>
              </template>
            </el-autocomplete>
            <i class="iconfont icon-mail"/>
          </div>
        </el-form-item>


        <el-form-item class="input-prepend restyle no-radius" prop="code">
          <div style="width: 100%;display: block;float: left;position: relative">
            <el-input type="text" placeholder="验证码" v-model="params.code"/>
            <i :class="isMobile?'icon-phone':'icon-mail'" class="iconfont "/>
          </div>
          <div class="btn" style="position:absolute;right: 0;top: 6px;width: 40%;">
            <a href="javascript:" type="button" @click="getCodeFun()" :value="codeTest" style="border: none">{{codeTest}}</a>
          </div>
        </el-form-item>

        <el-form-item class="input-prepend restyle" prop="password"
                      :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <div>
            <el-input type="password" placeholder="设置密码" v-model="params.password"/>
            <i class="iconfont icon-password"/>
          </div>
        </el-form-item>
        <el-form-item class="input-prepend" prop="checkPass"
        >
          <div>
            <el-input type="password" placeholder="确认密码" v-model="params.checkPass"/>
            <i class="iconfont icon-password"/>
          </div>
        </el-form-item>

        <div class="btn">
          <input type="button" class="sign-up-button" value="注册" @click="submitRegister()">
        </div>
        <p class="sign-up-msg">
          点击 “注册” 即表示您同意并愿意遵守简章
          <br>
          <a target="_blank" href="http://www.jianshu.com/p/c44d171298ce">用户协议</a>
          和
          <a target="_blank" href="http://www.jianshu.com/p/2ov8x3">隐私政策</a> 。
        </p>
      </el-form>
      <!-- 更多注册方式 -->
      <div class="more-sign">
        <h6>社交帐号直接注册</h6>
        <ul>
          <li><a id="weixin" class="weixin" target="_blank" href="http://localhost:8160/api/ucenter/wx/login"><i
            class="iconfont icon-weixin"/></a></li>
          <li><a id="qq" class="qq" target="_blank" href="#"><i class="iconfont icon-qq"/></a></li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import '~/assets/css/sign.css'
  import '~/assets/css/iconfont.css'
  import register from "../api/register";

  export default {
    layout: 'sign',
    data() {
      //昵称校验规则
      var checkNickName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('昵称不能为空'));
        } else {
          callback();
        }
      };
      //email校验规则
      // var checkEmail = (rule, value, callback) => {
      //   if (!value) {
      //     return callback(new Error('邮箱不能为空'));
      //   }
      //   setTimeout(() => {
      //     if (!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value))) {
      //       callback(new Error('邮箱格式错误'));
      //     } else {
      //         callback();
      //     }
      //   }, 1000);
      // };
      //验证码校验
      var checkCode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('验证码不能为空！'));
        } else {
          callback();
        }
        // else{
        //   if(this.realCode !== value){
        //     callback(new Error('验证码错误!'));
        //   }
        //   callback();
        // }
      };
      //密码校验
      var checkPassword1 = (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('密码不能为空'));
        } else {
          if (this.params.checkPass !== '') {
            this.$refs.userForm.validateField('checkPass');
          }
          callback();
        }
      };
      var checkPassword2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.params.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        params: {
          // mobile: '',
          code: '',//验证码
          nickname: '',//昵称
          password: '',//密码
          email: '',//邮箱
          checkPass: ''//确认密码
        },
        sending: true,      //是否发送验证码
        second: 60,        //倒计时间
        codeTest: '获取验证码',
        realCode: '',
        //TODO 考虑从数据库读取
        isMobile: false,//是否手机注册 否为邮箱
        rules: {
          nickname: [
            {validator: checkNickName, trigger: 'blur', required: true,}
          ],
          // email: [
          //   { validator: checkEmail, trigger: 'blur',required: true, }
          // ],
          password: [
            {validator: checkPassword1, trigger: 'blur', required: true,}
          ],
          checkPass: [
            {validator: checkPassword2, trigger: 'blur', required: true,}
          ],
          code: [
            {validator: checkCode, trigger: 'blur', required: true,}
          ],
        }
      }
    },
    methods: {
      //通过email发送验证码
      getCodeFun() {
        //sending = false
        //this.sending原为true,请求成功，!this.sending == true，主要是防止有人把disabled属性去掉，多次点击；
        if (!this.sending)
          return;

        //debugger
        // prop 换成你想监听的prop字段
        //const key = this.isMobile ? 'mobile' : 'email'
        this.$refs.userForm.validateField('email', (errMsg) => {
          //验证信息通过
          if (!errMsg) {
            //获取邮箱验证码
            register.sendEmail(this.params.email).then(res => {
              console.log("ffffff", res.data.data.code);
              this.realCode = res.data.data.code;
              this.sending = false;
              this.timeDown();
            });
          } else {
            this.$message({
              type: 'error',
              message: "邮箱格式错误"
            })
          }
        })
      },
      //注册提交的方法
      submitRegister() {
        this.$refs['userForm'].validate((valid) => {
          if (valid) {
            register.registerMember(this.params).then(resp => {
              if (resp.data.code === 20001) {
                this.$message({
                  type: 'error',
                  message: resp.data.message
                })
              } else {
                //提示注册成功
                this.$message({
                  type: 'success',
                  message: "注册成功"
                })
                this.$router.push({path: '/login'})
              }

            })
          }
        })
      },
      //验证码计时器
      timeDown() {
        let result = setInterval(() => {
          --this.second;
          this.codeTest = this.second
          this.disabled = true;
          if (this.second < 1) {
            clearInterval(result);
            this.sending = true;
            //this.disabled = false;
            this.second = 60;
            this.codeTest = "获取验证码"
          }
        }, 1000);

      },
      //邮箱格式限制
      handleSelect(item) {
        if (!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(item))) {
          return new Error('邮箱格式不正确')
        }
        this.params.email = item
      },
      //输入建议
      querySearch(queryString, cb) {
        const emailsuffix = ["@qq.com", "@163.com", "@gmail.com", "@yahoo.com"]
        let results = [];
        if ((queryString.split('@')).length - 1 === 0) {//判断@符号没出现 就添加邮箱建议
          for (let i = 0; i < emailsuffix.length; i++) {
            results[i] = queryString + emailsuffix[i];
          }
        }
        cb(results);
      },
    }
  }
</script>
